python求和函数怎么用

您所在的位置:网站首页 python sum求和字典 python求和函数怎么用

python求和函数怎么用

2023-09-13 23:13| 来源: 网络整理| 查看: 265

展开全部

sum(iterable[, start]) ,iterable为可迭代对象,如:

sum([ ], start) #iterable为list列表

sum(( ), start ) #iterable为tuple元组

......

最后的值 = 可迭代对象里面的数相加的值 + start的值

start默认为0,如果62616964757a686964616fe4b893e5b19e31333361313861不写就是0,为0时可以不写

即sum()的参数最多为两个,其中第一个必须为iterable,例如:

>>> sum([1, 2, 3,], 4)

10

>>> sum((1, 2), 3)

6

如果你写成sum([1,2,3]),start就是默认值 0

>>> sum([1, 2, 3])

6

>>> sum([ ], 2)

2

>>> sum(( ), )

0

>>> sum([1, 2] , 0)

3

当然iterable为dictionary字典时也是可以的:

>>> sum({1: 'b', 7: 'a'})

8

>>> sum({1:'b', 7:'a'}, 9)

17

下面这些写法目前是不被接受的(以list为例,其他iterable同理):

一、

>>> sum([1,2],[3,4])

Traceback (most recent call last):

File "", line 1, in

sum([1,2],[3,4])

TypeError: can only concatenate list (not "int") to list

二、

>>> sum(4,[1,2,3])

Traceback (most recent call last):

File "", line 1, in

sum(4,[1,2,3])

TypeError: 'int' object is not iterable

三、

>>> sum()

Traceback (most recent call last):

File "", line 1, in

sum()

TypeError: sum expected at least 1 arguments, got 0

四、

>>> sum(,2)

SyntaxError: invalid syntax

五、

>>> sum(1,3)

Traceback (most recent call last):

File "", line 1, in

sum(1,3)

TypeError: 'int' object is not iterable

附其官方解释:

>>> help(sum)

Help on built-in function sum in module builtins:

sum(...)

sum(iterable[, start]) -> value

Return the sum of an iterable of numbers (NOT strings) plus the value

of parameter 'start' (which defaults to 0). When the iterable is

empty, return start.



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3